<template>
  <el-row class="login-container" justify="center" align="middle">
    <el-card style="max-width: 480px">
      <template #header>
        <div class="card-header">
          <img :src="imgUrl" alt="" />
        </div>
      </template>
      <div class="jump-link">
        <el-link type="primary" @click="handleChange()">{{
          formType ? '返回登录' : '注册账号'
        }}</el-link>
        <el-form :model="loginForm" :rules="rules" ref="loginFormRef">
          <el-form-item prop="userName">
            <el-input
              v-model="loginForm.userName"
              placeholder="手机号"
              :prefix-icon="UserFilled"
            ></el-input>
          </el-form-item>
          <el-form-item prop="passWord">
            <el-input
              v-model="loginForm.passWord"
              type="password"
              placeholder="密码"
              :prefix-icon="Lock"
            ></el-input>
          </el-form-item>
          <el-form-item v-if="formType" prop="validCode">
            <el-input v-model="loginForm.validCode" placeholder="验证码" :prefix-icon="Lock">
              <template #append>
                <span @click="countdownChange">{{ countdown.validText }}</span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :style="{ width: '100%' }" @click="submitForm(loginFormRef)">
              {{ formType ? '注册' : '登录' }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </el-row>
</template>

<script setup>
  import { ref, reactive } from 'vue'
  import { UserFilled, Lock } from '@element-plus/icons-vue'
  import { getCode, userAuthentication, login } from '../../api'
  import { useRouter } from 'vue-router'
  const imgUrl = new URL('../../../public/images/login-head.png', import.meta.url).href
  const router = useRouter()

  // 表单数据
  const loginForm = reactive({
    userName: '',
    passWord: '',
    validCode: '',
  })

  // 用户名校验
  const validateUser = (rule, value, callback) => {
    // 不能为空
    if (value === '') {
      callback(new Error('请输入手机号'))
    } else {
      // 手机号格式校验
      const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
      phoneReg.test(value) ? callback() : callback(new Error('请输入正确的手机号'))
    }
  }
  // 密码校验
  const validatePass = (rule, value, callback) => {
    // 不能为空
    if (value === '') {
      callback(new Error('请输入密码'))
    } else {
      // 密码格式校验
      const phoneReg = /^[a-zA-Z0-9_-]{4,16}$/
      phoneReg.test(value)
        ? callback()
        : callback(new Error('密码格式不正确,需要4到16位字母、数字或下划线'))
    }
  }

  // 表单校验
  const rules = reactive({
    userName: [{ validator: validateUser, tigger: 'blur' }],
    passWord: [{ validator: validatePass, tigger: 'blur' }],
  })

  // 0-登录 1-注册
  const formType = ref(0)

  // 点击切换登录和注册
  const handleChange = () => {
    formType.value = formType.value ? 0 : 1
  }

  // 发送验证码
  let flag = false
  const countdown = reactive({ validText: '获取验证码', time: 60 })
  const countdownChange = () => {
    // 如果已发送就不处理
    if (flag) return
    const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/

    // 验证手机号格式
    if (!loginForm.userName || !phoneReg.test(loginForm.userName)) {
      return ElMessage.warning('请输入正确的手机号')
    }

    // 开始倒计时
    const timer = setInterval(() => {
      if (countdown.time <= 0) {
        countdown.validText = '获取验证码'
        countdown.time = 60
        flag = false
        clearInterval(timer)
      } else {
        countdown.time -= 1
        countdown.validText = `剩余${countdown.time}s`
      }
    }, 1000)
    flag = true
    getCode({ tel: loginForm.userName }).then(res => {
      if (res.data.code === 10000) {
        ElMessage.success('验证码已发送，请注意查收')
      }
    })
  }

  const loginFormRef = ref(null)
  // 提交表单
  const submitForm = async formEl => {
    if (!formEl) return
    // 手动触发校验
    await formEl.validate(valid => {
      if (valid) {
        console.log(loginForm, 'submit!')
        // 注册页面
        if (formType.value) {
          userAuthentication(loginForm).then(({ data }) => {
            if (data.code === 10000) {
              ElMessage.success('注册成功,请登录')
              formType.value = 0 // 切换到登录
            }
          })
        } else {
          // 登录页面
          login(loginForm).then(({ data }) => {
            if (data.code === 10000) {
              ElMessage.success('登录成功')
              console.log(data)
              // 将token和用户信息缓存到浏览器
              localStorage.setItem('pz_token', data.data.token)
              localStorage.setItem('pz_userInfo', JSON.stringify(data.data.userInfo))
              router.push('/')
            }
          })
        }
      } else {
        console.log('error submit!')
      }
    })
  }
</script>

<style lang="less" scoped>
  :deep(.el-card__header) {
    padding: 0;
  }
  .login-container {
    height: 100%;
    .card-header {
      background-color: #899fe1;
      img {
        width: 430px;
      }
    }
    .jump-link {
      text-align: right;
      margin-bottom: 10px;
    }
  }
</style>
